#include <stdio.h>
#include <conio.h>
#include <array>
#include <iostream>
using namespace std;

const int n=4;//物品数量
const double maxW=6;//背包容量

double v[4]={3,4,1,4};//各个物品的价值
double w[4]={2,3,1,5};//各个物品的重量
double perp[4];//单位物品价值排序后
int order[4]={0,1,2,3};//物品编号

class solution
{
public:
    double w=0;
    double p=0;
    array<bool,4> put;//设置是否装入
    void output()
    {
        for(int i=0;i<n;i++)
        {
            if(this->put[i])
                printf("%d ",order[i]);
        }
        cout<<": "<<this->w<<","<<this->p<<endl;
    }
};

solution cs;
solution bests;

//按单位价值排序
void knapsack()
{
    int i,j;
    int temporder = 0;
    double temp = 0.0;

    for(i=0;i<n;i++)
    {
        perp[i]=v[i]/w[i];
        cs.put[i]=false;
    }
    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
            if(perp[i]<perp[j]) //冒泡排序
        {
            temp = perp[i];
            perp[i]=perp[i];
            perp[j]=temp;

            temporder=order[i];
            order[i]=order[j];
            order[j]=temporder;
            temp = v[i];
            v[i]=v[j];
            v[j]=temp;

            temp=w[i];
            w[i]=w[j];
            w[j]=temp;
        }
    }
}

//计算上界函数
double bound(int i)
{
    double leftw= maxW-cs.w;
    double b = cs.p;
    b+=perp[i]*leftw;
    cs.output();
    cout<<"bound:"<<b<<" "<<perp[i]<<" "<<leftw<<endl;
    return b;
}

//回溯函数
void backtrack(int i)
{
    if(i==n)
    {
        if(bests.p<cs.p)
            bests=cs;
        return;
    }
    if(cs.w+w[i]<=maxW) //左剪枝
    {
        cs.w+=w[i];
        cs.p+=v[i];
        cs.put[i]=true;
        backtrack(i+1);
        cs.w-=w[i];
        cs.p-=v[i];
    }
    cs.put[i]=false;
    if(bound(i+1)>bests.p) //右剪枝
        backtrack(i+1);
}


int main()
{
    knapsack();
    backtrack(0);
    printf("best value\n");
    bests.output();
    return 0;
}
